package com.yycx.common.base.handler;

import com.yycx.common.base.entity.EntityMap;
import com.yycx.common.base.event.FlymeEvent;
import com.yycx.common.base.event.FlymeSyncEvent;
import com.yycx.common.base.listener.FlymeListener;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.utils.SpringContextHolder;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

/**
 * @author zyf
 */
@Component
public class FlymeEventHandler {
    /**
     * 监听FlymeEvent 并分发事件
     */
    @EventListener
    public void event(FlymeEvent flymeEvent) {
        EntityMap entityMap = flymeEvent.getEntityMap();
        String handlerName = flymeEvent.getHandlerName();
        if (FlymeUtils.isNotEmpty(handlerName)) {
            handlerEvent(handlerName, entityMap);
        }
    }

    /**
     * 监听FlymeEvent 并分发事件
     */
    @Async(value = "taskExecutor")
    @EventListener
    public void snycEvent(FlymeSyncEvent flymeSyncEvent) {
        EntityMap entityMap = flymeSyncEvent.getEntityMap();
        String handlerName = flymeSyncEvent.getHandlerName();
        if (FlymeUtils.isNotEmpty(handlerName)) {
            handlerEvent(handlerName, entityMap);
        }
    }

    private void handlerEvent(String handlerName, EntityMap entityMap) {
        if (FlymeUtils.isNotEmpty(handlerName)) {
            FlymeListener flymeListener = SpringContextHolder.getHandler(handlerName, FlymeListener.class);
            if (FlymeUtils.isNotEmpty(flymeListener)) {
                flymeListener.onMessage(entityMap);
            }
        }
    }
}
